package com.lglin.common.config.security.handler;

import com.lglin.bean.user.entity.SelfUserDetail;
import com.lglin.common.utils.jwt.JwtTokenUtil;
import com.lglin.common.utils.reponse.PrintOutUtil;
import com.lglin.common.utils.reponse.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class SelfAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetail);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("nickname",userDetail.getNickname());
        PrintOutUtil.printJsonOut(httpServletResponse, ResultBean.success().data(map).msg("登录成功！"));
    }
}
